package ru.incoremedia.gwttest.core.server.context;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import java.util.Locale;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ru.incoremedia.gwttest.core.client.security.UserRole;


public class RequestContext {

    private final static RequestContext instance = new RequestContext();

    public static RequestContext getInstance() {
        return instance;
    }

    private final ThreadLocal<HttpServletRequest> requestHolder = new ThreadLocal<HttpServletRequest>();
    
    private final ThreadLocal<HttpServletResponse> responseHolder = new ThreadLocal<HttpServletResponse>();

    public void setRequest(HttpServletRequest request) {
        requestHolder.set(request);
    }

    public HttpServletRequest getRequest() {
        return requestHolder.get();
    }

    public HttpServletResponse getResponse() {
        return responseHolder.get();
    }

    public UserRole getUserRole() {

        UserService userService = UserServiceFactory.getUserService();

        if(userService.isUserLoggedIn()) {
            if(userService.isUserAdmin()) {
                return UserRole.ROLE_ADMIN;
            } else {
                return UserRole.ROLE_USER;
            }
        }

        return UserRole.ROLE_GUEST;
    }

    public Locale getUserLocale() {
        String localeName = "en";

        for(Cookie cookie : getRequest().getCookies()) {
            if(cookie.getName().equals("locale")) {
                localeName = cookie.getValue();
                break;
            }
        }

        if(localeName.equals("default")) {
            localeName = "en";
        }
            
        return new Locale(localeName);
    }
}
